import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Input, message, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { listBookBorrow, updateBookBorrow } from '@/api/bookBorrowController';

interface BorrowData {
  id: string;
  bookid: string;
  bookname: string;
  user: {
    nickName: string;
  };
  borrowtime: string;
  shouldreturntime: string;
  status: number;
}

const statusConfig = {
  1: { text: '借阅中', color: 'bg-green-500 text-white' },
  2: { text: '已归还', color: 'bg-green-100 text-green-800' },
  3: { text: '已逾期', color: 'bg-red-100 text-red-800' },
  4: { text: '已续借', color: 'bg-yellow-100 text-yellow-800' },
  5: { text: '未审核', color: 'bg-gray-100 text-gray-800' }
};

export default function BorrowingManagement() {
  const [data, setData] = useState<BorrowData[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState({
    bookname: '',
    bookid: 0,
    current: 1,
    pageSize: 10
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await listBookBorrow(searchParams);
      if (res.code === 200) {
        setData(res.data.records);
      }
    } catch (error) {
      message.error('获取借阅列表失败');
    }
    setLoading(false);
  };

  const handleReturn = async (record: BorrowData) => {
    try {
      const res = await updateBookBorrow({
        id: record.id,
        status: 2
      });
      if (res.code === 200) {
        message.success('归还成功');
        fetchData();
      }
    } catch (error) {
      message.error('归还失败');
    }
  };

  const columns: ColumnsType<BorrowData> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '图书名称',
      dataIndex: 'bookname',
      key: 'bookname',
    },
    {
      title: '借阅人',
      dataIndex: ['user', 'nickName'],
      key: 'borrower',
    },
    {
      title: '借阅时间',
      dataIndex: 'borrowtime',
      key: 'borrowtime',
      render: (time) => new Date(time).toLocaleDateString(),
    },
    {
      title: '应还时间',
      dataIndex: 'shouldreturntime',
      key: 'shouldreturntime',
      render: (time) => new Date(time).toLocaleDateString(),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag className={statusConfig[status].color}>
          {statusConfig[status].text}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary"
            onClick={() => handleReturn(record)}
            disabled={record.status === 2}
          >
            归还
          </Button>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    fetchData();
  }, [searchParams]);

  return (
    <div className="p-4">
      <div className="mb-4 flex gap-4">
        <Input.Search
          placeholder="搜索书名"
          style={{ width: 200 }}
          onSearch={(value) => setSearchParams(prev => ({ ...prev, bookname: value }))}
        />
        <Input.Search
          placeholder="搜索书籍ID"
          style={{ width: 200 }}
          onSearch={(value) => setSearchParams(prev => ({ ...prev, bookid: Number(value) }))}
        />
      </div>
      <Table 
        columns={columns} 
        dataSource={data} 
        loading={loading}
        rowKey="id"
        pagination={{
          total: data.length,
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          onChange: (page) => setSearchParams(prev => ({ ...prev, current: page }))
        }}
      />
    </div>
  );
} 